//
//  MineViewController.m
//  OrderFood
//
//  Created by xiaofang wang on 2018/10/22.
//  Copyright © 2018年 zhiyuan. All rights reserved.
//

#import "MineViewController.h"
#import "LoginViewController.h"
#import "BaseNaviViewController.h"
#import "HandInViewController.h"
#import "FinishOrderViewController.h"
#import "SettlementViewController.h"
#import "SetViewController.h"

//12-29切换根视图控制器
#import "BaseTabBarViewController.h"
#import "WorkViewController.h"
#import "CommissionListViewController.h"

//model
#import "HomeModel.h"

@interface MineViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *mineTableView;
@property(nonatomic,strong)UIView *headerView;
@property(nonatomic,copy)NSArray *titleAry;

/**1.头像*/
@property (nonatomic, strong) UIImageView *iconIv;
/**2.骑手姓名*/
@property (nonatomic, strong) UILabel *nameLabel;
/**3.骑手工号*/
@property (nonatomic, strong) UILabel *jobNumberLabel;
/**4.完成单数*/
@property (nonatomic, strong) UILabel *danShuLb;
/**5.今日收益*/
@property (nonatomic, strong) UILabel *todayProfitLb;
/**6.奔跑里程*/
@property (nonatomic, strong) UILabel *distanceLb;

/**模型*/
@property (nonatomic, strong) HomeModel *model;
@end

@implementation MineViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    /// 第一个参数是当下的控制器适配iOS11 一下的，第二个参数表示scrollview或子类
    AdjustsScrollViewInsetNever(self,self.mineTableView);
    [self loadMyData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.mineTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-TabBar_HEIGHT) style:UITableViewStylePlain];
    self.mineTableView.dataSource = self;
    self.mineTableView.delegate = self;
    self.mineTableView.backgroundColor = BACKGROUNDCOLOR;
    self.mineTableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:self.mineTableView];
//    self.titleAry = @[@"今日异常上报次数",@"外卖现金上交",@"佣金结算账单",@"设置"];
    self.titleAry = @[@"今日异常上报次数",@"佣金结算账单",@"设置"];
    
    [self setUIofheaderView];
}

-(void)setUIofheaderView{
    
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 400)];
    self.headerView.backgroundColor = BACKGROUNDCOLOR;
    self.mineTableView.tableHeaderView = self.headerView;
    //骑手基本信息
//    CGFloat topH = SCREEN_WIDTH*420/750
    CGFloat topH = 210;
    UIImageView *bgImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, topH)];
    bgImgView.image = IMAGE(@"b");
    bgImgView.userInteractionEnabled = YES;
    [self.headerView addSubview:bgImgView];
    
    UIImageView *userImgView = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-75)/2.0, SafeAreaTopHeight-20, 75, 75)];
    userImgView.layer.cornerRadius = GetHeight(userImgView)/2.0;
    userImgView.image = IMAGE(@"tx");
    self.iconIv = userImgView;
    [bgImgView addSubview:userImgView];
    
    UILabel *nameLb = [[UILabel alloc] initWithFrame:CGRectMake(0, GetMaxY(userImgView)+15, SCREEN_WIDTH, 20)];
    nameLb.font = FONT(15);
    nameLb.textColor = WHITECOLOR;
    nameLb.textAlignment = NSTextAlignmentCenter;
    nameLb.text = @"张三";
    self.nameLabel = nameLb;
    [bgImgView addSubview:nameLb];
    
    UILabel *jobNumberLb = [[UILabel alloc] initWithFrame:CGRectMake(0, GetMaxY(nameLb)+10, SCREEN_WIDTH, 20)];
    jobNumberLb.font = FONT(15);
    jobNumberLb.textColor = WHITECOLOR;
    jobNumberLb.textAlignment = NSTextAlignmentCenter;
    jobNumberLb.text = @"工号：251478";
    self.jobNumberLabel = jobNumberLb;
    [bgImgView addSubview:jobNumberLb];
    
    
    //退出
    UIButton *exitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    exitBtn.frame = CGRectMake(SCREEN_WIDTH - 80, SafeArealanHeight, 80, 44);
    [exitBtn layoutButtonForTitle:@"退出" titleFont:FONT(12) image:IMAGE(@"tuichu") gapBetween:4 layType:1];
    [bgImgView addSubview:exitBtn];
    [exitBtn addTarget:self action:@selector(exitAction) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *chengjiuLb = [[UILabel alloc] initWithFrame:CGRectMake(15, topH, SCREEN_WIDTH, 35)];
    chengjiuLb.font = FONT(15);
    chengjiuLb.textColor = themeTextColor;
    chengjiuLb.text = @"今日成就";
    [self.headerView addSubview:chengjiuLb];
    
    UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(0, GetMaxY(chengjiuLb), SCREEN_WIDTH, 100)];
    subView.backgroundColor = WHITECOLOR;
    [self.headerView addSubview:subView];
    for (int i = 0; i < 2; i++) {
        [QTTools tool_addLineWithFrame:CGRectMake(SCREEN_WIDTH/3.0+SCREEN_WIDTH/3.0*i, 15, 1, 70) superView:subView];
    }
    
    NSArray *topAry = @[@"完成单数",@"获得收益",@"奔跑里程"];
    NSArray *dataAry = @[@"103",@"€398.0",@"35.9km"];
    for (int i = 0; i < 3; i++) {
        UIView *smallView = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/3.0*i, 0, SCREEN_WIDTH/3.0, 100)];
        smallView.tag = 100+i;
        [subView addSubview:smallView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionOfTap:)];
        [smallView addGestureRecognizer:tap];
        UILabel *topLb = [[UILabel alloc] initWithFrame:CGRectMake(0, 25, SCREEN_WIDTH/3.0, 20)];
        topLb.font = FONT(15);
        topLb.textColor = themeTextColor;
        topLb.textAlignment = NSTextAlignmentCenter;
        topLb.text = topAry[i];
        [smallView addSubview:topLb];
        
        UILabel *dataLb = [[UILabel alloc] initWithFrame:CGRectMake(0, GetMaxY(topLb)+15, SCREEN_WIDTH/3.0, 20)];
        dataLb.font = FONT(20);
        dataLb.textColor = BLACKCOLOR;
        dataLb.textAlignment = NSTextAlignmentCenter;
        dataLb.text = dataAry[i];
        
        if (i==0) {
            self.danShuLb = dataLb;
        }else if (i==1){
            self.todayProfitLb = dataLb;
        }else if (i==2){
            self.distanceLb = dataLb;
        }
        [smallView addSubview:dataLb];
    }
    
    self.headerView.height = GetMaxY(subView)+10;
}
- (void)updatemyUIWithHomeModel:(HomeModel *)model {

    NSURL *iconurl = [NSURL URLWithString:model.head];
    [self.iconIv sd_setImageWithURL:iconurl placeholderImage:[UIImage imageNamed:@"tx"]];
    
    self.nameLabel.text = model.name;
    self.jobNumberLabel.text = [NSString stringWithFormat:@"工号:%@",model.riderId];
    self.danShuLb.text = [NSString stringWithFormat:@"%@",model.order]; //今日单数
    self.todayProfitLb.text = [NSString stringWithFormat:@"€%.2f",[model.salary floatValue]]; //今日收益
    self.distanceLb.text = [NSString stringWithFormat:@"%.2fkm",[model.distance floatValue]];
}

-(void)actionOfTap:(UITapGestureRecognizer *)sender{
    UIView *view = sender.view;
    if (view.tag == 100) {
        FinishOrderViewController *vc = [FinishOrderViewController new];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}
#pragma mark - Action
-(void)exitAction{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"退出登录" message:@"是否退出当前账号" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
       NSLog(@"点击了取消");
    }];
    WeakObj(self)
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        LoginViewController *vc = [[LoginViewController alloc] init];
        BaseNaviViewController *navc = [[BaseNaviViewController alloc] initWithRootViewController:vc];
        [weakself presentViewController:navc animated:YES completion:nil];
        [USERDEFAULT setBool:NO forKey:LOGIN];
        [USERDEFAULT removeObjectForKey:TOKEN_KEY];
    }];
 
    //把action添加到actionSheet里
    [alertVC addAction:action1];
    [alertVC addAction:action2];
    //相当于之前的[actionSheet show];
    [self presentViewController:alertVC animated:YES completion:nil];
}


#pragma mark - UITableViewDelegate,UITableViewDataSource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.titleAry.count;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = self.titleAry[indexPath.row];
        cell.textLabel.font = FONT(15);        
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    //异常上报次数
    if (indexPath.row == 0) {
        if ([self.model.feedback isKindOfClass:[NSNull class]] || self.model.feedback == nil) {
            cell.detailTextLabel.text = @"0";
            cell.detailTextLabel.font = FONT(15);
        }else {
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",self.model.feedback];
        }
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    [tableView deselectRowAtIndexPath:indexPath animated:YES]; //sb
    if (indexPath.row == 0) {
//        HandInViewController *vc = [[HandInViewController alloc] init];
//        vc.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:vc animated:YES];
        
        //12-29切换根视图控制器:工作->异常上报,tips setter 方法肯定不viewDidload方法先走。
        [self changeToWorkingController];
        
    }else if (indexPath.row == 1) {
//        SettlementViewController *vc = [[SettlementViewController alloc] init];
//        vc.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:vc animated:YES];
        
        CommissionListViewController *vc = [CommissionListViewController new];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else if (indexPath.row == 2) {
        SetViewController *vc = [SetViewController new];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}
////分割线补全
- (void)viewDidLayoutSubviews {

    if ([self.mineTableView respondsToSelector:@selector(setLayoutMargins:)]) {

        self.mineTableView.layoutMargins = UIEdgeInsetsZero;
    }
    if ([self.mineTableView respondsToSelector:@selector(setSeparatorInset:)]) {

        self.mineTableView.separatorInset = UIEdgeInsetsZero;
    }
}

//- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
//
//    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
//
//        cell.layoutMargins = UIEdgeInsetsZero;
//    }
//
//    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
//        cell.separatorInset = UIEdgeInsetsZero;
//    }
//}



- (UIStatusBarStyle)preferredStatusBarStyle {
    
    return UIStatusBarStyleLightContent;
    
}


#pragma mark - 网络请求
- (void)loadMyData {
    
    [HUD showOperateBegin:@""]; //加载动画
    
    [NetWork requestMySucessBlock:^(NSDictionary * _Nonnull response) {
        [HUD dismissHuD];
        
        if (RES_SUCESS) {
            NSDictionary *resDic = response[@"data"];
            self.model = [HomeModel mj_objectWithKeyValues:resDic];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self updatemyUIWithHomeModel:self.model];
            });
            
        }else {
            [IndicatorManager showMessage:MESSAGE];
        }
    } failBlock:^(NSString * _Nonnull message) {
        [HUD dismissHuD];
    }];
}

#pragma mark - 12-29 切换根视图控制器
- (void)changeToWorkingController {
    //12-29切换根视图控制器:工作->异常上报
    //切换跟视图控制器
    BaseTabBarViewController *baseTabBarVC = [[BaseTabBarViewController alloc] init];
    
    baseTabBarVC.selectedIndex = 1;
    NSLog(@"%@",baseTabBarVC.selectedViewController); //WorkViewController
    BaseNaviViewController *baseNavVC = (BaseNaviViewController *)baseTabBarVC.selectedViewController;
    
    NSLog(@"%@",baseNavVC.topViewController); //WorkViewController
    WorkViewController *workVC = (WorkViewController *)baseNavVC.topViewController;
    workVC.changeIndex = 1;
    
    //        WorkViewController *workVC = [[WorkViewController alloc] init];
    //        workVC.changeIndex = 1; //切换下标
    [UIApplication sharedApplication].keyWindow.rootViewController = baseTabBarVC;
}
@end
